package db_server_sqlserver

import (
	"PackingScanApp/json_conf_get"
	"context"
	"database/sql"
	"fmt"
	"net/url"

	_ "github.com/denisenkom/go-mssqldb"
)

var (
	server_l    = json_conf_get.Getconf().SqlServerDBHost
	server_xinc = json_conf_get.Getconf().SqlServerDBHost_XinC

	port     = json_conf_get.Getconf().SqlServerDBPort
	user     = json_conf_get.Getconf().SqlServerDBUser
	password = json_conf_get.Getconf().SqlServerDBPassword
	database = json_conf_get.Getconf().SqlServerDBName
	cangQu   = json_conf_get.Getconf().CangQu
	//测试库连接字段，后期加功能时使用
	server_test   = ""
	port_test     = 1433
	user_test     = "sa"
	password_test = ""
	database_test = ""
)

type MSSql struct {
	Conn   *sql.DB
	Ctx    context.Context
	Cancel context.CancelFunc
}

/**
* 新建数据库连接（正式库）
**/
func (mssql *MSSql) NewMSsql() {
	server := server_l
	if cangQu == 1 {
		server = server_xinc
	}
	query := url.Values{}
	query.Add("database", database)
	query.Add("encrypt", "disable") //是否加密（设置为否），此行代码必须设置，否则连接不上数据库;
	u := &url.URL{
		Scheme: "sqlserver",
		User:   url.UserPassword(user, password),
		Host:   fmt.Sprintf("%s:%d", server, port),
		// Path:  instance, // if connecting to an instance instead of a port
		RawQuery: query.Encode(),
	}
	//建立连接
	if db, err := sql.Open("sqlserver", u.String()); err == nil {
		mssql.Conn = db
	} else {
		panic(err)
	}
	mssql.Ctx, mssql.Cancel = context.WithCancel(context.Background()) //管道
}

//新建数据库连接（测试库）
func (mssql *MSSql) NewMSsql_Test() {
	query := url.Values{}
	query.Add("database", database_test)
	query.Add("encrypt", "disable") //是否加密（设置为否），此行代码必须设置，否则连接不上数据库;
	u := &url.URL{
		Scheme: "sqlserver",
		User:   url.UserPassword(user_test, password_test),
		Host:   fmt.Sprintf("%s:%d", server_test, port_test),
		// Path:  instance, // if connecting to an instance instead of a port
		RawQuery: query.Encode(),
	}
	//建立连接
	if db, err := sql.Open("sqlserver", u.String()); err == nil {
		mssql.Conn = db
	} else {
		panic(err)
	}
	mssql.Ctx, mssql.Cancel = context.WithCancel(context.Background()) //管道
}

/**
* 关闭数据库连接
**/
func (mssql *MSSql) CloseMSsql() {
	mssql.Conn.Close()
	mssql.Cancel()
}
